import Sprite from "../base/sprite";
import Card from "../card/card";
import { SCREEN_WIDTH, SCREEN_HEIGHT } from "../render";

const BACKGROUND_IMAGE_SRC = "images/slot2.png";
const BACKGROUND_WIDTH = 500;
const BACKGROUND_HEIGHT = 132;

/**
 * 游戏背景类
 * 提供 update 和 render 函数实现无限滚动的背景功能
 */
export default class Slot extends Sprite {
  constructor() {
    super(BACKGROUND_IMAGE_SRC, BACKGROUND_WIDTH, BACKGROUND_HEIGHT);
  }
  loadAllImagePromise() {
    return this.loadImagePromise;
  }
  update() {
    if (GameGlobal.databus.isGameOver) {
      return;
    }
  }
  //检查选中卡片是否有三个相同可以消除
  checkMatches(slotCardsdData) {
    const countMap = slotCardsdData.reduce((acc, item) => {
      acc[item.picIndex] = (acc[item.picIndex] || 0) + 1;
      return acc;
    }, {});

    Object.entries(countMap).forEach(([type, count]) => {
      if (count >= 3) {
        for (let i = slotCardsdData.length - 1; i >= 0; i--) {
          const item = slotCardsdData[i];
          if (item.picIndex === type) {
            slotCardsdData.splice(i, 1);
          }
        }
      }
    });
  }
  renderSlotCrads(ctx, arr) {

    // GameGlobal.slot.left,
    //   GameGlobal.slot.top,
    //   GameGlobal.slot.width,
    //   GameGlobal.slot.height

    const left = GameGlobal.slot.left + GameGlobal.px2dpr(16)
    const top = GameGlobal.slot.top - GameGlobal.px2dpr(1);

    const w = GameGlobal.card.width;
    const itemGap = GameGlobal.slot.itemGap;
    const height = GameGlobal.slot.height;

    for (let i = 0; i < arr.length; i++) {
      const item = arr[i];
      const { zIndex } = item;
      // zIndex > this.MaxZIndex && (this.MaxZIndex = zIndex);

      const card = new Card(
        left + i * w + (i + 1) * itemGap,
        top + (height - GameGlobal.card.height) / 2,
        item.picIndex
      );

      // (async () => {

      /* card.on("load", () => {
        card.render(ctx, zIndex);
      }); */
      card.render(ctx, zIndex);
    }
  }

  update(ctx) {
    // 绘制卡槽背景
    this.render(ctx);
    // 检测是否有三个，有三个清除
    this.checkMatches(GameGlobal.databus.slotCardsdData);
    // 绘制卡槽上的卡片
    this.renderSlotCrads(ctx, GameGlobal.databus.slotCardsdData);
  }

  /**
   * 背景图重绘函数
   */
  render(ctx) {
    // 绘制第一张背景
    ctx.drawImage(
      this.img,
      0,
      0,
      this.width,
      this.height,
      GameGlobal.slot.left,
      GameGlobal.slot.top,
      GameGlobal.slot.width,
      GameGlobal.slot.height
    );
  }
}
